/**
 * Created by yongwang on 2015/6/15.
 */
var toolUtil = require('../../common/utils/toolUtil');
var async = require('async');
var mysqlUtil = require('../../common/utils/mysqlUtil');
var communityService = require('../communityService');
var Users = mongoose.model('user');
var Question = mongoose.model('question');
var ActivityNeighbour = mongoose.model('activity_neighbour');

Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //�·�
        "d+": this.getDate(), //��
        "h+": this.getHours(), //Сʱ
        "m+": this.getMinutes(), //��
        "s+": this.getSeconds(), //��
        "q+": Math.floor((this.getMonth() + 3) / 3), //����
        "S": this.getMilliseconds() //����
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

exports.getGeekList = function (map, page, callback) {
    var offset = (Number(page) - 1) * 10;
    var opt = {
        userType: "talent"
    },
        listPageSize = 10;

    if(map.communityId)opt.community = map.communityId;
    //if(map.starttime)opt.starttime = map.starttime;
    //if(map.endtime)opt.endtime = map.endtime;
    //if(map.status)opt.status = map.status;
    if(map.nickname)opt.nickName = new RegExp(map.nickname);
    if(map.phone)opt.mobilePhone = map.phone;

    Users.find(opt).skip(offset).limit(listPageSize).sort({
        dateCreated: -1
    }).populate('community', 'communityName').exec(function (err, result) {
        async.series([
            function (callbackInner){
                var questionArray = [];
                async.each(result, function (item, callbackInner) {
                    Question.find({
                        createdBy: item._id
                    }).exec(function (err, question) {//praiseCount
                        var replies = 0;//回复数
                        var praiseCount = 0;//点赞数
                        var level = 0;//精华帖数
                        question.forEach(function(ite){
                            if(ite.replies)replies += ite.replies.length;
                            if(ite.praiseCount)praiseCount += ite.praiseCount;
                            if(ite.level)level++;
                        });

                        questionArray.push({q: question.length,r: replies,p: praiseCount,l: level});
                        callbackInner();
                    })
                }, function (err) {
                    //callback(err, result);
                    callbackInner(err, questionArray);
                });
            },
            function (callbackInner){
                var activityNeighbour = [];
                async.each(result, function (item, callbackInner) {
                    ActivityNeighbour.find({
                        createdBy: item._id
                    }).exec(function (err, activity) {
                        var replies = 0;
                        var praiseCount = 0;
                        var level = 0;
                        activity.forEach(function(ite){
                            if(ite.replies)replies += ite.replies.length;
                            if(ite.praiseCount)praiseCount += ite.praiseCount;
                            if(ite.level)level++;
                        });
                        activityNeighbour.push({a: activity.length,r: replies,p: praiseCount,l: level});
                        callbackInner();
                    })
                }, function (err) {
                    //callback(err, result);
                    callbackInner(err, activityNeighbour);
                });
            },
            function (callbackInner){
                callbackInner(err, result);
            }
        ], callback);
            //callback(err, result);
        });



    //,
    //function (callbackInner){
    //    var sql = "SELECT sum(change_value) scoreGained FROM 66xiaoqu_db.score_sn as score"
    //    sql += " inner join 66xiaoqu_dwh.users as users on score.user_id = users._id WHERE community='" + commId + "'";
    //    sql += " and change_value > 0"
    //    sql += startdatecondition + enddatecondition
    //    mysqlUtil.query(sql, function(err, result){
    //        if(result[0] == undefined || result[0] == null)
    //            callbackInner(err, 0)
    //        else
    //            callbackInner(err, result[0].scoreGained)
    //    })
    //},
    //function (callbackInner){
    //    var sql = "SELECT sum(change_value) scoreConsumed FROM 66xiaoqu_db.score_sn as score"
    //    sql += " inner join 66xiaoqu_dwh.users as users on score.user_id = users._id WHERE community='" + commId + "'";
    //    sql += " and change_value < 0"
    //    sql += startdatecondition + enddatecondition
    //    mysqlUtil.query(sql, function(err, result){
    //        if(result[0] == undefined || result[0] == null)
    //            callbackInner(err, 0)
    //        else
    //            callbackInner(err, result[0].scoreConsumed)
    //    })
    //},
    //function (callbackInner){
    //    var sql = "select sum(after_current_value) currentvalue from (select * from"
    //    sql += "(SELECT user_id, after_current_value, CASE when update_time > 10000000000 then from_unixtime(update_time / 1000) else from_unixtime(update_time) end as time FROM 66xiaoqu_db.score_sn as score"
    //    sql += " inner join 66xiaoqu_dwh.users as users on score.user_id = users._id WHERE community='" + commId + "'";
    //    //sql += startdatecondition + enddatecondition
    //    sql += " order by time desc) as t group by user_id) as u"
    //    mysqlUtil.query(sql, function(err, result){
    //        if(result[0] == undefined || result[0] == null)
    //            callbackInner(err, 0)
    //        else
    //            callbackInner(err, result[0].currentvalue)
    //    })
    //}


    //.populate('community', 'communityName').populate('tag', 'value').populate('createdBy', 'userType nickName')
    //    .populate('replies.repliedBy', '_id community nickName images authenticationStatus')
    //    .populate('partake.user', '_id community nickName images authenticationStatus')
    //    .
};